package com.tyqx.hashchainbiz.controller.jzt;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tyqx.hashchainbean.module.HashChainStatistics;
import com.tyqx.hashchainbean.module.JZTCodeCirculation;
import com.tyqx.hashchainbean.module.TrackUser;
import com.tyqx.hashchainbean.vo.JZTCodeCirculationAndGS1VO;
import com.tyqx.hashchainbean.vo.JZTCodeCirculationVO;
import com.tyqx.hashchainbean.vo.JZTLogisticsVO;
import com.tyqx.hashchainbean.vo.MongoDbInfoVO;
import com.tyqx.hashchainbiz.controller.config.JwtTokenUtil;
import com.tyqx.hashchainbiz.service.*;
import com.tyqx.hashchainutil.common.mongodb.ImagePathHashValueUtil;
import hashchainutil.common.Dto;
import hashchainutil.common.DtoUtil;
import hashchainutil.common.EmptyUtils;
import org.hyperledger.fabric.sdk.security.CryptoPrimitives;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/JZTApi/codeCirculation")
@CrossOrigin
public class JZTCodeCirculationController {

    @Resource
    private JZTCodeCirculationService jztCodeCirculationService;

    @Resource
    private JZTCodeCirculationRelationshipService jztCodeCirculationRelationshipService;

    @Resource
    private TrackUserService trackUserService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private MysqlDataBaseAndMongDbConfigService mysqlDataBaseAndMongDbConfigService;

    @RequestMapping(value = "/addJZTCodeCirculation", method = RequestMethod.POST)
    @ResponseBody
    public Dto addJZTCodeCirculation(@RequestBody JZTCodeCirculation jztCodeCirculation, HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String tokenUserName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        String userName = jztCodeCirculation.getUserName();
        TrackUser trackUser = trackUserService.getUserByCode(userName);
        if (EmptyUtils.isEmpty(trackUser)) {
            String msg = "用户找不到";
            return DtoUtil.returnFail(msg, "100006");
        }

        if (!tokenUserName.equals(userName)) {
            String msg = "用户名跟token用户名不匹配";
            return DtoUtil.returnFail(msg, "100005");
        }
        String msg = "";

        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = sdf.parse(sdf.format(currentDate));
        Date updateTime = createTime;

        List<JZTCodeCirculation> jztLogisticsList=new ArrayList<>();
        boolean flag=false;
        jztLogisticsList.add(jztCodeCirculation);

        MongoDbInfoVO mongoDbInfoVO = new MongoDbInfoVO();
        if (jztLogisticsList.size() > 0) {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .create();
            String jztLogisticsListStr = gson.toJson(jztLogisticsList);
            CryptoPrimitives suite = new CryptoPrimitives();
            suite.init();
            String hashValue = ImagePathHashValueUtil.getHashValue(jztLogisticsListStr, suite);

            mongoDbInfoVO.setHashValue(hashValue);
            mongoDbInfoVO.setInfoList(jztLogisticsList);
            mongoDbInfoVO.setInfoTableName("jzt_code_circulation");

            String collName = "jztCodeCirculationList";


            double dataCount = jztLogisticsList.size();
            String dataType = "jztCodeCirculationList";
            HashChainStatistics hashChainStatistics = new HashChainStatistics();
            hashChainStatistics.setDataCount(dataCount);
            hashChainStatistics.setDataType(dataType);
            hashChainStatistics.setUserName(jztLogisticsList.get(0).getUserName());
            hashChainStatistics.setCreateTime(createTime);
            hashChainStatistics.setUpdateTime(updateTime);
            flag=mysqlDataBaseAndMongDbConfigService.insertDataCountAndMongoDB(hashChainStatistics, collName, mongoDbInfoVO);
        }
        if (flag) {
            msg = "信息上链成功";
            return DtoUtil.returnSuccess(msg);
        } else {
            msg = "信息上链失败";
            return DtoUtil.returnFail(msg, "100001");
        }
    }

    @RequestMapping(value = "/batchAddJZTCodeCirculation", method = RequestMethod.POST)
    @ResponseBody
    public Dto batchAddJZTCodeCirculation(@RequestBody List<JZTCodeCirculation> jztCodeCirculationList, HttpServletRequest request) throws Exception {
        // verify token username against data username
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        TrackUser trackUser = trackUserService.getUserByCode(userName);
        List<JZTCodeCirculation> jztLogisticsListError = new ArrayList<>();
        int size = jztCodeCirculationList.size();
        for (int i = 0; i < size; i++) {
            JZTCodeCirculation jztCodeCirculation = jztCodeCirculationList.get(i);
            if (EmptyUtils.isEmpty(trackUser) || !userName.equals(jztCodeCirculation.getUserName())) {
                jztLogisticsListError.add(jztCodeCirculation);
            }
        }
        if (jztLogisticsListError.size() > 0) {
            for (int j = 0; j < jztLogisticsListError.size(); j++) {
                jztCodeCirculationList.remove(jztLogisticsListError.get(j));
            }
        }
        String msg = "";

        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = sdf.parse(sdf.format(currentDate));
        Date updateTime = createTime;

        MongoDbInfoVO mongoDbInfoVO = new MongoDbInfoVO();
        if (jztCodeCirculationList.size() > 0) {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd HH:mm:ss")
                    .create();
            String jztLogisticsListStr = gson.toJson(jztCodeCirculationList);
            CryptoPrimitives suite = new CryptoPrimitives();
            suite.init();
            String hashValue = ImagePathHashValueUtil.getHashValue(jztLogisticsListStr, suite);

            mongoDbInfoVO.setHashValue(hashValue);
            mongoDbInfoVO.setInfoList(jztCodeCirculationList);
            mongoDbInfoVO.setInfoTableName("jzt_code_circulation");

            String collName = "jztCodeCirculationList";


            double dataCount = jztCodeCirculationList.size();
            String dataType = "jztCodeCirculationList";
            HashChainStatistics hashChainStatistics = new HashChainStatistics();
            hashChainStatistics.setDataCount(dataCount);
            hashChainStatistics.setDataType(dataType);
            hashChainStatistics.setUserName(jztCodeCirculationList.get(0).getUserName());
            hashChainStatistics.setCreateTime(createTime);
            hashChainStatistics.setUpdateTime(updateTime);
            /*Integer flag=hashChainStatisticsService.add(hashChainStatistics);
            flag=0;
            if (flag == 0){
                throw new Exception("record statistcs error");
            }
            mongoDBUtil.insertOne(collName,mongoDbInfoVO);*/
            mysqlDataBaseAndMongDbConfigService.insertDataCountAndMongoDB(hashChainStatistics, collName, mongoDbInfoVO);
        }

        if (jztLogisticsListError.size() == 0 && EmptyUtils.isNotEmpty(mongoDbInfoVO.getId())) {
            msg = "信息上链成功";
            return DtoUtil.returnSuccess(msg);
        } else if (jztCodeCirculationList.size() == 0 && jztLogisticsListError.size() > 0) {
            msg = "信息上链失败,信息包含的用户名不正确";
            return DtoUtil.returnFail(msg, "100001");
        } else {
            msg = "success: " + jztCodeCirculationList.size() + ", fail: " + jztLogisticsListError.size() + ",用户名不正确信息上链失败";
            return DtoUtil.returnSuccess(msg, "100002");
        }
    }

    @RequestMapping(value = "/getJZTCodeCirculationByTraceabilityCode", method = RequestMethod.POST)
    @ResponseBody
    public Dto getJZTCodeCirculationByTraceabilityCode(@RequestParam(value = "traceabilityCode", required = true) String traceabilityCode,HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);
        List<String> parentTraceabilityCodeStr = jztCodeCirculationRelationshipService.getParentTraceabilityCodeByTraceabilityCode(traceabilityCode);
        String[] parentTraceabilityCodes = parentTraceabilityCodeStr.get(0).split(",");
        List<String> traceabilityCodes = new ArrayList<>();
        for (int i = 0; i < parentTraceabilityCodes.length; i++) {
            if (EmptyUtils.isNotEmpty(parentTraceabilityCodes[i])) {
                traceabilityCodes.add(parentTraceabilityCodes[i]);
            }
        }
        //traceabilityCodes.add(traceabilityCode);
        List<JZTCodeCirculationVO> jztLogistics = jztCodeCirculationService.getJZTCodeCirculationByTraceabilityCode(traceabilityCodes,userName);
        if (jztLogistics.size() > 0) {
            return DtoUtil.returnSuccess("查询成功", jztLogistics);
        } else {
            return DtoUtil.returnSuccess("未查询到记录", "");
        }
    }

    @RequestMapping(value = "/getJZTCodeCirculationAndGS1ByTraceabilityCode", method = RequestMethod.POST)
    @ResponseBody
    public Dto getJZTCodeCirculationAndGS1ByTraceabilityCode(@RequestParam(value = "traceabilityCode", required = true) String traceabilityCode,HttpServletRequest request) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        String userName = jwtTokenUtil.getUsernameFromToken(jwtToken);

        List<String> parentTraceabilityCodeStr = jztCodeCirculationRelationshipService.getParentTraceabilityCodeByTraceabilityCode(traceabilityCode);
        String[] parentTraceabilityCodes = parentTraceabilityCodeStr.get(0).split(",");
        List<String> traceabilityCodes = new ArrayList<>();
        for (int i = 0; i < parentTraceabilityCodes.length; i++) {
            if (EmptyUtils.isNotEmpty(parentTraceabilityCodes[i])) {
                traceabilityCodes.add(parentTraceabilityCodes[i]);
            }
        }
        //traceabilityCodes.add(traceabilityCode);
        List<JZTCodeCirculationAndGS1VO> jztCodeCirculationAndGS1VOList = jztCodeCirculationService.grantGetJZTCodeCirculationAndGS1ByTraceabilityCode(traceabilityCodes,userName);
        if (jztCodeCirculationAndGS1VOList.size() > 0) {
            return DtoUtil.returnSuccess("查询成功", jztCodeCirculationAndGS1VOList);
        } else {
            return DtoUtil.returnSuccess("未查询到记录", "");
        }
    }
}
